<template>
    <div class="image-upload">
      <el-upload
        v-model:file-list="fileList"
        action="/api/upload"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
        :on-success="handleSuccess"
        :before-upload="beforeUpload"
        :limit="limit"
        :multiple="multiple"
      >
        <el-icon><Plus /></el-icon>
      </el-upload>
  
      <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image" />
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { ref, watch } from 'vue'
  import { Plus } from '@element-plus/icons-vue'
  
  const props = defineProps({
    modelValue: {
      type: Array,
      default: () => []
    },
    limit: {
      type: Number,
      default: 10
    },
    multiple: {
      type: Boolean,
      default: true
    }
  })
  
  const emit = defineEmits(['update:modelValue'])
  
  const fileList = ref([])
  const dialogVisible = ref(false)
  const dialogImageUrl = ref('')
  
  watch(() => props.modelValue, (newVal) => {
    fileList.value = newVal
  }, { immediate: true })
  
  watch(fileList, (newVal) => {
    emit('update:modelValue', newVal)
  })
  
  const handleRemove = (uploadFile, uploadFiles) => {
    fileList.value = uploadFiles
  }
  
  const handlePictureCardPreview = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url
    dialogVisible.value = true
  }
  
  const handleSuccess = (response, uploadFile, uploadFiles) => {
    fileList.value = uploadFiles
  }
  
  const beforeUpload = (file) => {
    const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png'
    const isLt5M = file.size / 1024 / 1024 < 5
  
    if (!isJPGOrPNG) {
      ElMessage.error('图片只能是 JPG/PNG 格式!')
      return false
    }
    if (!isLt5M) {
      ElMessage.error('图片大小不能超过 5MB!')
      return false
    }
    return true
  }
  </script>
  
  <style scoped>
  .image-upload {
    width: 100%;
  }
  </style>